package com.myfojing.mycloud;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import io.realm.Realm;
import io.realm.RealmResults;

/* 数据采集背景服务 */

public class DataService extends Service {

    // 线程池
    ScheduledExecutorService scheduler;
    List<Sensirion> sensirions = new ArrayList<>();
    private String TAG = "我的服务：";
    private DataBinder dataBinder = new DataBinder();
    private int sample_interval;
    // 写入数据间隔
    private int record_interval;
    private int elapsed = 0;
    private boolean blRecord = false;
    // database
    private Realm realm;

    public DataService() {
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate() 执行");
        realm = Realm.getDefaultInstance();
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return dataBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() 执行");
        // 读采样间隔
        String interval = getSharedPreferences("profile", MODE_PRIVATE).getString("sample_interval", "1");
        sample_interval = Integer.parseInt(interval) * 10;

        interval = getSharedPreferences("profile", MODE_PRIVATE).getString("record_interval", "2");
        record_interval = Integer.parseInt(interval) * 20;

        task_read();

        // 前台服务
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("采集服务");
        try {
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            Notification notification = builder.build();
            startForeground(1, notification);
        } catch (NullPointerException e) {
            Log.d(TAG, "空指针错误。");
        }

        Log.d(TAG, "启动服务");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy() 执行");
        if (scheduler != null) {
            scheduler.shutdownNow();
        }
        realm.close();
        super.onDestroy();
    }

    private void task_read() {
        // 定时任务
        //size_thread_pool = 2 * getNumberOfCores() + 1;
        if (scheduler != null) {
            scheduler.shutdownNow();
        }
        // 从数据库读设备
        get_device();
        // 定时任务
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate
                (new Runnable() {
                    public void run() {
                        // 记录时间
                        elapsed += sample_interval;
                        //Log.d(TAG, Integer.toString(elapsed));
                        if (elapsed >= record_interval) {
                            elapsed = 0;
                            blRecord = true;
                        }
                        // 发起请求
                        for (int i = 0; i < sensirions.size(); i++) {
                            Sensirion sensirion = sensirions.get(i);
                            sensirion.read_th(getApplication(), sample_interval, record_interval);
                        }
                        // end:run
                    }
                }, 0, sample_interval, TimeUnit.SECONDS);
    }

    private void get_device() {

        sensirions.clear();
        RealmResults<Sensirion> mySensirions = realm.where(Sensirion.class).findAll();
        for (int i = 0; i < mySensirions.size(); i++) {
            Sensirion mySensirion = mySensirions.get(i);
            mySensirion.setElapsed(0);
            sensirions.add(mySensirion);
        }
    }

    // 时间
    String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return format.format(new Date());
    }

    /* 自定义 */
    class DataBinder extends Binder {
        void change_interval(int in1, int in2) {
            Log.d(TAG, "change_interval() 执行");
            sample_interval = in1 * 30;
            record_interval = in2 * 60;
            task_read();
        }

        void refresh() {
            task_read();
        }
    }
    // end
}
